import api from './api'
const _AKHttp = {}
wx.$AKHttp = init(api)
 
// 请求路径(根据需求修改)
let host = 'https://www.ggdzhj.com'

// 封装get和post方法(可替换为自定义的请求工具)
const httpTool = {
  get(params){
    return new Promise((resolve, reject)=>{
      wx.request({
        url: params.url,
        method: 'GET',
        data: params.data,
        header: params.header,
        success:(res)=>{
          resolve(res)
        },
        fail:(err)=>{
          reject(err)
        }
      })
    })
  },
  post(params){
    return new Promise((resolve, reject)=>{
      wx.request({
        url: params.url,
        method: 'POST',
        data: params.data,
        header: params.header,
        success:(res)=>{
          resolve(res)
        },
        fail:(err)=>{
          reject(err)
        }
      })
    })
  }
}

// ======================  核心代码  ======================
/**
 * 请求例子:
 * 1. 最简请求 [注释: 默认取第一配置(存在GET,POST请求方法情况)]
 * 1.1 post请求
 *    (api例子:viewSetting:{post:"/video/viewSetting"})
 *    const p = { name: "AK" }
 *    wx.$AKHttp.viewSetting(p).then(res => console.log)
 * 1.2 get请求
 *    (api例子:getViewByVideoId:{get:"/video/viewCountByVideoId/{id}")
 *    const id = "738123"
 *    wx.$AKHttp.getViewByVideoId(id).then(res => console.log)
 *
 * 2. 配置请求
 * 参数 method 请求方法 (默认取配置第一个)
 * 参数 params 请求参数
 * 参数 urlParams 替换URL参数
 * 参数 httpToolParams 请求工具自定义参数
 * const p = { name: "AK" }
 * wx.$AKHttp.billingSetting( { method: 'POST', params: p, urlParams: {id: 9999} } ).then(res => console.log)
 */
function init(requestConfig) {
  for (const _apiKey in requestConfig) {
    const _apiConfig = requestConfig[_apiKey]
    const request = function(requestParams = {}) {
      // 自定义参数
      const {
        params, //请求参数
        urlParams, //路由参数
        method,
        httpToolParams
      } = requestParams
      // 判断是否持有特定参数
      if (params || urlParams || method || httpToolParams) {
        // 配置请求
        return buildRequest({ _apiConfig, _apiKey, ...requestParams })
      } else {
        // 最简请求
        return buildSimpleRequest(_apiConfig, requestParams)
      }
    }
    _AKHttp[_apiKey] = request
  }
  return _AKHttp
}

// 最简请求
function buildSimpleRequest(_apiConfig, requestParams) {
  const method = Object.keys(_apiConfig)[0]
  let url = _apiConfig[method]
  // 1.是否需要替换url参数
  if (method == 'get' || method == 'GET') url = replaceUrlParams(url, requestParams)
  // 2.是否拼接请求域名
  if(url.length > 4 && url.slice(0,4) != "http" ){
    url = host + url
  }
  return httpTool[method]({
    url,
    data: requestParams,
  })
}

// 配置请求
function buildRequest({
  _apiConfig,
  _apiKey,
  params,
  urlParams,
  method,
  //请求工具自定义参数
  httpToolParams
}) {
  // 1.请求方法
  const requestMethod = method || Object.keys(_apiConfig)[0]
  // 2.请求URL
  let requestUrl = _apiConfig[requestMethod]
  if (!requestUrl) {
    return console.error('配置中没有找到该Method方法')
  }
  // 2.1判断是否需要替换URL中的变量
  if (urlParams) requestUrl = replaceUrlParams(requestUrl, urlParams)
  // 3.请求数据
  const data = params

  // 4.是否拼接请求域名
  if(requestUrl.length > 4 && requestUrl.slice(0,4) != "http" ){
    requestUrl = host + requestUrl
  }
  
  return httpTool[requestMethod]({
    url: requestUrl,
    data,
    ...httpToolParams
  })
}

// 替换URL参数方法
function replaceUrlParams(requestUrl, urlParams) {
  
  const paramsType = typeof urlParams
  if(paramsType === 'string' || paramsType === 'number') {
    requestUrl = requestUrl.replace(/{[a-zA-Z]+}/g,urlParams)
  }else{
    for (const key in urlParams) {
      const urlKey = `{${key}}`
      const item = urlParams[key]
      requestUrl = requestUrl.replace(urlKey, item)
    }
  }
  return requestUrl
}
